package com.yanchangapp.ui.fragment.purchase;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.yanchangapp.R;
import com.yanchangapp.adapter.ContractListAdapter;
import com.yanchangapp.adapter.PsOrderAdapter;
import com.yanchangapp.model.bean.ContractListBean;
import com.yanchangapp.model.bean.FilterBean;
import com.yanchangapp.ui.activity.purchase.POrderListActivity;
import com.yanchangapp.ui.activity.purchase.contract.ContractDetailActivity;
import com.yanchangapp.ui.activity.purchase.contract.ContractEditActivity;
import com.yanchangapp.ui.activity.purchase.contract.ContractEnsureActivity;
import com.yanchangapp.ui.activity.purchase.contract.ContractListActivity;
import com.yanchangapp.ui.presenter.ContractListFgPresenter;
import com.yanchangapp.ui.view.ContractListFgView;
import com.zxl.baselib.ui.base.BaseFragment;
import com.zxl.baselib.util.ui.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;


/**
 * Created by apple on 2019-08-19.
 * description: 合同列表Fragment....
 */
public class ContractListFragment extends BaseFragment<ContractListFgView, ContractListFgPresenter> implements ContractListFgView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.tvDes)
    TextView tvDes;
    @BindView(R.id.llEmptyMsg)
    LinearLayout llEmptyMsg;

    private String title;
    public static final String TITLE = "title";
    public static final String VALUE = "VALUE";
    private static final String TAG = "tab页";
    private boolean isShow = false;
    private boolean isLoading = false;
    private ContractListAdapter mContractListAdapter;
    private List<ContractListBean> mContractListBeans = new ArrayList<>();
    // 请求体需要的各个参数
    private String paramsValue;
    private String keywords = null;
    private int curPage = 1;
    private String startTime = null;
    private String endTime = null;
    private int position = -1;

    @Override
    public void init() {
        if (getArguments() != null) {
            title = getArguments().getString(TITLE);
            // 赋予值....
            paramsValue = getArguments().getString(VALUE);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isShow = isVisibleToUser;
        if (isVisibleToUser) {
            if (!TextUtils.isEmpty(title)) {
                isLoading = true;
                loadList();
            } else {
                isLoading = false;
            }
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_contract_list;
    }

    @Override
    protected ContractListFgPresenter createPresenter() {
        return new ContractListFgPresenter((ContractListActivity) getActivity());
    }


    @Override
    public void initView(View rootView) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mContractListAdapter = new ContractListAdapter(R.layout.item_contract_list, mContractListBeans);
        recyclerView.setAdapter(mContractListAdapter);
        if (isShow && !isLoading) {
            loadList();
        }
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            // 直接刷新列表即可
            refreshList(true);
        });

        tvDes.setText("暂无合同");

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
            }
        });

        // 设置监听...
        mRxManager.on(ContractListActivity.NOTIFY_CONTRACT_FILTER_DATA, new Consumer<FilterBean>() {
            @Override
            public void accept(FilterBean filterBean) throws Exception {
                keywords = filterBean.getKeywords();
                startTime = filterBean.getStartTime();
                endTime = filterBean.getEndTime();
                if (title.equals(filterBean.getTitle())){
                    loadList();
                }
            }
        });

        mContractListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ContractDetailActivity.show(getActivity(),mContractListBeans.get(position).getId());
            }
        });

        mContractListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tvModify){
                ContractEditActivity.show(getActivity(),mContractListBeans.get(position).getId());
            }else if (view.getId() == R.id.tvSubmit){
                ContractEnsureActivity.show(getActivity(),mContractListBeans.get(position).getId());
            }
        });
    }

    // 加载更多
    private void loadMore() {
        // 添加数量
        curPage++;
        mPresenter.queryPsList(paramsValue, startTime, endTime, keywords, curPage, false);
    }

    /**
     * 刷新数据...
     */
    private void refreshList(boolean isPulling) {
        curPage = 1;
        refreshLayout.resetNoMoreData();
        mPresenter.queryPsList(paramsValue, startTime, endTime, keywords, curPage, isPulling);
    }

    private void loadList() {
        // 滑动到了第一个....
        recyclerView.scrollToPosition(0);
        refreshList(false);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {

    }

    // 设置各种显示的状态
    private void showContent(){
        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }

        if (refreshLayout.getVisibility() == View.GONE){
            refreshLayout.setVisibility(View.VISIBLE);
        }

        if (llEmptyMsg.getVisibility() == View.VISIBLE){
            llEmptyMsg.setVisibility(View.GONE);
        }

    }

    private void showEmpty(){
        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }

        if (refreshLayout.getVisibility() == View.VISIBLE){
            refreshLayout.setVisibility(View.GONE);
        }

        if (llEmptyMsg.getVisibility() == View.GONE){
            llEmptyMsg.setVisibility(View.VISIBLE);
        }
    }

    private void showError(){
        if (llErrorNetwork.getVisibility() == View.GONE){
            llErrorNetwork.setVisibility(View.VISIBLE);
        }

        if (refreshLayout.getVisibility() == View.VISIBLE){
            refreshLayout.setVisibility(View.GONE);
        }

        if (llEmptyMsg.getVisibility() == View.VISIBLE){
            llEmptyMsg.setVisibility(View.GONE);
        }
    }

    // 进行刷新
    public void handleRefresh() {
        loadList();
    }

    @Override
    public void queryContractSuccess(List<ContractListBean> mContractBeans) {
        if (curPage == 1) {
            Log.e("列表刷新", "进来了");
            mContractListBeans.clear();
            refreshLayout.finishRefresh();
            if (mContractBeans == null || mContractBeans.size() == 0) {
                // 空布局
                showEmpty();
            } else {
                // 含有内容
                showContent();
                Log.e("列表刷新", "内容来了");
                mContractListBeans.addAll(mContractBeans);
            }
            mContractListAdapter.notifyDataSetChanged();
        } else {
            if (mContractBeans == null || mContractBeans.size() == 0) {
                // 下拉加载无更多内容
                refreshLayout.finishLoadMoreWithNoMoreData();
                curPage--;
            } else {
                // 含有内容
                mContractListBeans.addAll(mContractBeans);
                mContractListAdapter.notifyDataSetChanged();
                refreshLayout.finishLoadMore();
            }
        }
    }

    @Override
    public void queryContractFailure(String err) {
        UIUtils.showToast(err);
        showError();
        if (curPage == 1) {
            refreshLayout.finishRefresh();
        } else {
            curPage--;
            refreshLayout.finishLoadMore();
        }
    }
}
